import json
import os
import time
import base64
import jenkins
from io import BytesIO

from matplotlib.figure import Figure

from flask import Flask, jsonify, request
from flask_cors import CORS
from flask_cors import cross_origin

app = Flask(__name__, static_folder='/')
CORS(app, supports_credentials=True)


@app.route('/benchmark')
def index():
    results = {'msg': 'ok', 'content': []}
    root = 'D:\\tgraph\\jenkins'
    files = os.listdir(root)
    for f in files:
        path = root + os.sep + f
        benchmarkFilePath = path + os.sep + 'benchmark.json'
        if os.path.isdir(path) and f.startswith('b_') and os.path.exists(benchmarkFilePath):
            mtime = time.ctime(os.path.getmtime(benchmarkFilePath))
            fsize = os.path.getsize(benchmarkFilePath)
            if fsize > 0:
                results['content'].append([f, mtime, fsize])
    return jsonify(results)


@app.route('/jenkins_jobs')
def jenkins_jobs():
    results = {'msg': 'ok', 'content': {
        # 'deploy': jenkins.job_info('milestone-deploy'),
        'build': jenkins.job_info('milestone-build-master'),
        'test': jenkins.job_info('test'),
        # 'validate': jenkins.job_info('validate')
    }}
    return jsonify(results)


# @cross_origin(supports_credentials=True)
@app.route('/build_job/<name>', methods=['POST'])
def build_job(name):
    ret = {'msg': 'ok', 'err': 0}
    if request.get_data() is None:
        ret['err'] = '400'
        ret['msg'] = '请求参数为空'
        return json.dumps(ret, ensure_ascii=False)
    req = json.loads(request.get_data())
    return jsonify(jenkins.buildJob(name, req))


@app.route("/plot")
def hello():
    fig = Figure()
    ax = fig.subplots()
    ax.plot([1, 2])
    # Save it to a temporary buffer.
    buf = BytesIO()
    fig.savefig(buf, format="png")
    # Embed the result in the html output.
    raw = base64.b64encode(buf.getbuffer()).decode("ascii")
    return f"<img src='data:image/png;base64,{raw}'/>"


@app.route('/post', methods=['POST'])
def data():
    data = json.loads(request.get_data())
    return_dict = {'code': '200', 'msg': '修改成功', 'result': False}
    # 判断入参是否存在
    if request.get_data() is None:
        return_dict['code'] = '5004'
        return_dict['msg'] = '请求参数为空'
        return json.dumps(return_dict, ensure_ascii=False)
        # 通过.get_data方法获得携带的数据
    # get_Data =


if __name__ == "__main__":
    app.run(debug=True)
